package com.bw.module_home.ui

import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.BackgroundColorSpan
import android.text.style.ImageSpan
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.lib_common.arout.ARouterPath
import com.bw.lib_mvicore.ui.BaseMviActivity
import com.bw.module_home.R
import com.bw.module_home.databinding.HomeActivityHomeDetailBinding
import com.bw.module_home.model.entity.SimpleVideoEntity
import com.google.android.material.tabs.TabLayout
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.DanmakuTimer
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.IDisplayer
import master.flame.danmaku.danmaku.model.android.BaseCacheStuffer
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.model.android.SpannedCacheStuffer
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser
import master.flame.danmaku.danmaku.util.IOUtils
import java.io.IOException
import java.io.InputStream
import java.net.MalformedURLException
import java.net.URL

@Route(path = ARouterPath.PAGE_HOME_DETAIL)
class HomeDetailActivity : BaseMviActivity() {
    private lateinit var binding: HomeActivityHomeDetailBinding

    /**
     * 弹幕上下文
     */
    private lateinit var context: DanmakuContext

    /**
     * 弹幕解析器
     */
    private var parser: BaseDanmakuParser? = null

    /**
     * 简介Fragment
     */
    private lateinit var descriptionFragment: HomeDetailDescriptionFragment

    /**
     * 评论Fragment
     */
    private lateinit var commentFragment: HomeDetailCommentFragment

    @Autowired
    lateinit var data:SimpleVideoEntity

    /**
     * 图文混排适配器
     */
    private val mCacheStufferAdapter: BaseCacheStuffer.Proxy = object : BaseCacheStuffer.Proxy() {
        private var mDrawable: Drawable? = null
        override fun prepareDrawing(danmaku: BaseDanmaku, fromWorkerThread: Boolean) {
            if (danmaku.text is Spanned) { // 根据你的条件检查是否需要需要更新弹幕
                // FIXME 这里只是简单启个线程来加载远程url图片，请使用你自己的异步线程池，最好加上你的缓存池
                object : Thread() {
                    override fun run() {
                        val url = "http://www.bilibili.com/favicon.ico"
                        var inputStream: InputStream? = null
                        var drawable = mDrawable
                        if (drawable == null) {
                            try {
                                val urlConnection = URL(url).openConnection()
                                inputStream = urlConnection.getInputStream()
                                drawable = BitmapDrawable.createFromStream(inputStream, "bitmap")
                                mDrawable = drawable
                            } catch (e: MalformedURLException) {
                                e.printStackTrace()
                            } catch (e: IOException) {
                                e.printStackTrace()
                            } finally {
                                IOUtils.closeQuietly(inputStream)
                            }
                        }
                        if (drawable != null) {
                            drawable.setBounds(0, 0, 100, 100)
                            val spannable = createSpannable(drawable)
                            danmaku.text = spannable
                            if (binding.dvHomeDetail != null) {
                                binding.dvHomeDetail.invalidateDanmaku(danmaku, false)
                            }
                            return
                        }
                    }
                }.start()
            }
        }

        override fun releaseResource(danmaku: BaseDanmaku) {
            // TODO 重要:清理含有ImageSpan的text中的一些占用内存的资源 例如drawable
        }
    }

    fun createDanmakuParser():BaseDanmakuParser{
        return object :BaseDanmakuParser(){
            override fun parse(): IDanmakus {
                return Danmakus()
            }
        }
    }

    override fun generateViewModel() {

    }

    override fun getLayoutView(): View {
        binding = HomeActivityHomeDetailBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun handleState() {

    }

    override fun injectARout() {
        super.injectARout()
        ARouter.getInstance().inject(this)
    }

    override fun initView() {
        super.initView()
        //tab
        initTab()

        //创建fragment
        initFragments()

        //初始化弹幕
        initDanMu()
    }

    private fun initDanMu() {
        // 设置最大显示行数
        // 设置最大显示行数
        val maxLinesPair = HashMap<Int, Int>()
        maxLinesPair[BaseDanmaku.TYPE_SCROLL_RL] = 7 // 滚动弹幕最大显示5行

        // 设置是否禁止重叠
        val overlappingEnablePair = HashMap<Int, Boolean>()
        overlappingEnablePair[BaseDanmaku.TYPE_SCROLL_RL] = true
        overlappingEnablePair[BaseDanmaku.TYPE_FIX_TOP] = true
        //初始化弹幕的环境
        context = DanmakuContext.create()
        context.setDanmakuStyle(IDisplayer.DANMAKU_STYLE_SHADOW, 10f)
            .setDuplicateMergingEnabled(false)
            .setScrollSpeedFactor(5.2f)
            .setScaleTextSize(1.2f)
            .setCacheStuffer(SpannedCacheStuffer(), mCacheStufferAdapter) // 图文混排使用SpannedCacheStuffer
            //              .setCacheStuffer(new BackgroundCacheStuffer())  // 绘制背景使用BackgroundCacheStuffer
            .setMaximumLines(maxLinesPair)
            .preventOverlapping(overlappingEnablePair)
            .setDanmakuMargin(10)
        if(binding.dvHomeDetail != null){
            parser = createDanmakuParser()
            binding.dvHomeDetail.setCallback(object :master.flame.danmaku.controller.DrawHandler.Callback{
                override fun prepared() {
                    binding.dvHomeDetail.start()
                    addDanmaku(true)
                    addDanmaku(true)
                    addDanmaku(true)
                    addDanmaKuShowTextAndImage(true)
                }

                override fun updateTimer(timer: DanmakuTimer?) {

                }

                override fun danmakuShown(danmaku: BaseDanmaku?) {

                }

                override fun drawingFinished() {

                }
            })

            binding.dvHomeDetail.prepare(parser, context)
            binding.dvHomeDetail.showFPS(true)
            binding.dvHomeDetail.enableDanmakuDrawingCache(true)
        }
    }

    private fun initFragments() {
        val bundle = Bundle()
        bundle.putParcelable("data",data)
        descriptionFragment = HomeDetailDescriptionFragment()
        descriptionFragment.arguments = bundle
        commentFragment = HomeDetailCommentFragment()
        commentFragment.arguments = bundle
        //默认添加简介
        supportFragmentManager.beginTransaction()
            .add(R.id.fl_home_detail_content,descriptionFragment)
            .commitAllowingStateLoss()
    }

    private fun initTab() {
        binding.tabHomeDetailType.addTab(binding.tabHomeDetailType.newTab().setText(getString(R.string.home_detail_descriptioin)))
        binding.tabHomeDetailType.addTab(binding.tabHomeDetailType.newTab().setText(getString(R.string.home_detail_recomment)))
    }

    override fun initEvent() {
        super.initEvent()
        binding.tabHomeDetailType.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab) {
                when (tab.position) {
                    0 -> {
                        switchFragment(R.id.fl_home_detail_content,
                            commentFragment,
                            descriptionFragment)
                    }
                    1 -> {
                        switchFragment(R.id.fl_home_detail_content,
                            descriptionFragment,
                            commentFragment)
                    }
                }

            }
            override fun onTabUnselected(tab: TabLayout.Tab?) {

            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }
        })
        //弹幕开关
        binding.switchHomeDetailBulletscreen.setOnCheckedChangeListener { _, isChecked ->
            if(isChecked){
                binding.dvHomeDetail.show()
            }else{
                binding.dvHomeDetail.hide()
            }
        }
    }

    /**
     * 发送弹幕
     */
    private fun addDanmaku(islive: Boolean) {
        val danmaku = context.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)
        if (danmaku == null || binding.dvHomeDetail == null) {
            return
        }
        // for(int i=0;i<100;i++){
        // }
        danmaku.text = "这是一条弹幕" + System.nanoTime()
        danmaku.padding = 5
        danmaku.priority = 0 // 可能会被各种过滤器过滤并隐藏显示
        danmaku.isLive = islive
        danmaku.time = binding.dvHomeDetail.getCurrentTime() + 1200
        danmaku.textSize = 25f * (parser!!.displayer.density - 0.6f)
        danmaku.textColor = Color.RED
        danmaku.textShadowColor = Color.WHITE
        // danmaku.underlineColor = Color.GREEN;
        danmaku.borderColor = Color.GREEN
        binding.dvHomeDetail.addDanmaku(danmaku)
    }

    /**
     * 发送弹幕：图文混排
     */
    private fun addDanmaKuShowTextAndImage(islive: Boolean) {
        val danmaku = context.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL)
        val drawable = resources.getDrawable(R.drawable.ic_agree)
        drawable.setBounds(0, 0, 100, 100)
        val spannable: SpannableStringBuilder = createSpannable(drawable)
        danmaku.text = spannable
        danmaku.padding = 5
        danmaku.priority = 1 // 一定会显示, 一般用于本机发送的弹幕
        danmaku.isLive = islive
        danmaku.time = binding.dvHomeDetail.getCurrentTime() + 1200
        danmaku.textSize = 25f * (parser!!.displayer.density - 0.6f)
        danmaku.textColor = Color.RED
        danmaku.textShadowColor = 0 // 重要：如果有图文混排，最好不要设置描边(设textShadowColor=0)，否则会进行两次复杂的绘制导致运行效率降低
        danmaku.underlineColor = Color.GREEN
        binding.dvHomeDetail.addDanmaku(danmaku)
    }
    private fun createSpannable(drawable: Drawable): SpannableStringBuilder {
        val text = "bitmap"
        val spannableStringBuilder = SpannableStringBuilder(text)
        val span = ImageSpan(drawable) //ImageSpan.ALIGN_BOTTOM);
        spannableStringBuilder.setSpan(span, 0, text.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        spannableStringBuilder.append("图文混排")
        spannableStringBuilder.setSpan(
            BackgroundColorSpan(Color.parseColor("#8A2233B1")),
            0,
            spannableStringBuilder.length,
            Spannable.SPAN_INCLUSIVE_INCLUSIVE)
        return spannableStringBuilder
    }
    override fun onPause() {
        super.onPause()
        if (binding.dvHomeDetail != null && binding.dvHomeDetail.isPrepared()) {
            binding.dvHomeDetail.pause()
        }
    }

    override fun onResume() {
        super.onResume()
        if (binding.dvHomeDetail != null && binding.dvHomeDetail.isPrepared() && binding.dvHomeDetail.isPaused()) {
            binding.dvHomeDetail.resume()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (binding.dvHomeDetail != null) {
            // dont forget release!
            binding.dvHomeDetail.release()
//            binding.dvHomeDetail = null
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        if (binding.dvHomeDetail != null) {
            // dont forget release!
            binding.dvHomeDetail.release()
//            binding.dvHomeDetail = null
        }
    }
}